﻿using SoccerGameSpider.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using ScrapperBase;

namespace SoccerGameSpider
{
    public class GermanyMatchLoader: MatchLoader
    {
        private HtmlNode teamDiv;
        private HtmlNode eventTable;

        protected override string UrlFormat
        {
            get { return "http://www.kicker.de/{0}"; }
        }

        protected override TeamStats GetTeamStats(HtmlDocument matchDoc, HomeAway homeAway)
        {
            var table = matchDoc.DocumentNode.SelectSingleNode("//table[@class='tStat' and @summary='Vereinsliste']");
            var teamDivs = table.SelectNodes(".//div[@class='aufstellung_team']");

            this.teamDiv = teamDivs[0];
            Team team = this.match.HomeTeam;

            if (homeAway == HomeAway.Away)
            {
                teamDiv = teamDivs[1];
                team = this.match.AwayTeam;
            }

            this.eventTable = matchDoc.DocumentNode.SelectSingleNode("//table[@class='tStat tLive']");

            var teamStats = new TeamStats();

            teamStats.HomeAway = homeAway;
            teamStats.Team = team;
            this.LoadPlayers(teamStats, this.match.MatchTime);

            return teamStats;
        }

        private EventType ConvertFromImage(string imgUrl)
        {
            string imageName = imgUrl.Substring(imgUrl.LastIndexOf('/') + 1);

            switch (imageName)
            {
                case "ergtyp_1-m.png":
                    return EventType.Goal;
                //case "":
                //    return EventType.OwnGoal;
                case "ergtyp_2-m.png":
                    return EventType.YellowCard;
                case "ergtyp_3-m.png":
                case "ergtyp_4-m.png":
                    return EventType.RedCard;
                case "ergtyp_5-m.png":
                    return EventType.SwitchOut;
                default:
                    return EventType.Unknown;
            }
        }

        public void LoadPlayers(TeamStats teamStats, DateTime matchTime)
        {
            var containers = teamDiv.SelectNodes("./div/div");

            var topContainer = containers[0];

            var playerNodes = topContainer.SelectNodes("./div/div[@class='spielerdiv']");

            foreach (var node in playerNodes)
            {
                var playerKey = node.ChildNodes[0].Attributes[1].Value.Split('/')[8];
                var playerName = HtmlEntity.DeEntitize(node.ChildNodes[0].InnerText);

                PlayerStats playerStats = new PlayerStats();
                playerStats.Player = teamStats.Team.GetPlayer(playerKey, playerName, matchTime);
                playerStats.TopBench = TopBench.Top;

                teamStats.Players.Add(playerStats);
            }

            var benchContainer = containers[1];

            if (benchContainer.FirstChild.InnerText.Contains("Einwechslungen"))
            {
                var benchNodes = benchContainer.SelectNodes(".//div/a");

                for (int i = 0; i < benchNodes.Count(); i += 2)
                {
                    var playerName = HtmlEntity.DeEntitize(benchNodes[i].InnerText);
                    var playerKey = benchNodes[i].Attributes[1].Value.Split('/')[8];

                    PlayerStats playerStats = new PlayerStats();
                    playerStats.Player = teamStats.Team.GetPlayer(playerKey, playerName, matchTime);
                    playerStats.TopBench = TopBench.Bench;

                    teamStats.Players.Add(playerStats);
                }
            }

            ParseStatsTable(teamStats);

            teamStats.YellowCards = teamStats.Players.Sum(ps => ps.YellowCards);
            teamStats.RedCards = teamStats.Players.Sum(ps => ps.RedCards);
        }

        private void ParseStatsTable(TeamStats teamStats)
        {
            string filter = ".//tr[td/div/div/img]";

            var nodes = eventTable.SelectNodes(filter);

            foreach (var node in nodes)
            {
                string infoPath = @"./td[@class='lttdspereig']/div/div[@class='ltereigkurz']/b";
                var infoNode = node.SelectSingleNode(infoPath);

                var count = infoNode.ChildNodes.Count;

                if (!infoNode.ChildNodes[count - 1].InnerText.Contains(teamStats.Team.Name))
                {
                    continue;
                }

                var player = infoNode.SelectSingleNode("./a[position() = 1]").InnerText;
                PlayerStats ps = teamStats.Players.Find(p => p.Player.Name == player);

                var minute = node.SelectSingleNode(".//td[@class='lttdspinfo']/div/div/div[position()=3]").InnerText;
                var imgUrl = node.SelectSingleNode(".//td[@class='lttdspinfo']/div/div[@class='lttdspst']/div[@class='ltereig']").FirstChild.Attributes[0].Value;
                var type = ConvertFromImage(imgUrl);


                switch (type)
                {
                    case EventType.Goal:
                        ps.Goals++;
                        break;
                    case EventType.OwnGoal:
                        ps.OwnerGoals++;
                        break;
                    case EventType.RedCard:
                        ps.RedCards++;
                        break;
                    case EventType.YellowCard:
                        ps.YellowCards++;
                        break;
                    case EventType.SwitchOut:
                        ps.IsSwitchOut = true;
                        break;
                    default:
                        break;
                }

                MatchEvent matchEvent = new MatchEvent();
                matchEvent.EventType = type;
                matchEvent.EventMinute = int.Parse(minute.Split('.')[0]);

                ps.MatchEvents.Add(matchEvent);
            }
        }
    }
}
